// 引入数据库
const con = require("../db/db.js");
const moment = require("moment");
const bcrypt = require("bcryptjs")
const showregister = (req, res) => {
    res.render("./user/register.ejs", {})
}
const showlogin = (req, res) => {
    res.render("./user/login.ejs", {})
}
// 注册
const register = (req, res) => {
    let bloguser = req.body;
    // console.log(bloguser);
    let mi = 10;//幂次
    // 密码加密
    bcrypt.hash(bloguser.password, mi, (err, pwd) => {
        // console.log(pwd);
        if (err) return console.log("加密失败");
        // 加密成功则将加密后的密码赋值给原密码
        bloguser.password = pwd;
        let sql = "select count(*) as cc from blog_users where username =?";
        con.query(sql, bloguser.username, (err, result) => {
            if (err) return res.send({ static: 500, msg: "查重失败" });
            // console.log(result);
            if (result[0].cc == 1) return res.send({ static: 501, msg: "用户名已注册" });
            bloguser.ctime = moment().format("YYYY-MM-DD HH:mm:ss");
            let sql1 = "insert into blog_users set ?";
            con.query(sql1, bloguser, (err, result1) => {
                if (err) return res.send({ static: 502, msg: "添加失败" });
                res.send({ static: 200, msg: "注册成功" });
            })
        })
    })
}
// 登录
const login = (req, res) => {
    let user = req.body;
    // console.log(user);
    if (user.username.trim() == "" || user.password.trim() == "") {
        return res.send({ status: 500, msg: "用户名不能为空" });
    }
    let sql = "select * from blog_users where username=?";
    con.query(sql, user.username, (err, result) => {
        if (err) return res.send({ status: 501, msg: "查询登录失败" });
        // console.log(result);
        if (result.length == 0) return res.send({ status: 502, msg: "用户名不存在" })
        // 将加密密码和输入密码进行比对
        bcrypt.compare(user.password, result[0].password, (err, jieguo) => {
            if (!jieguo) return res.send({ status: 503, msg: "密码错误" });
            // 在session里存储信息
            req.session.user = result[0];
            req.session.islogin = true;
            // console.log(req.session);
            res.send({ status: 200, msg: "登陆成功" });
        })
    })
}
// 注销
const logout = (req, res) => {
    req.session.destroy(function () {
        res.redirect("/");
    })
}
const ctr = {
    showregister,
    showlogin,
    register,
    login,
    logout
}
module.exports = ctr;